
define(['ionic'], function () {
    angular.module('BUSContacts.services', [])
        .factory('ContactService', ['$q', 'OperaterUtil',
            function ($q, OperaterUtil) {
                var o = {},
                    contactsCache = {},
                    userInfo = {},
                    sealCache = {};

                o.getDepartmentContacts = function () {
                    var defer = $q.defer();

                    if (contactsCache.departmentContacts) {
                        defer.resolve(angular.copy(contactsCache.departmentContacts));
                    } else {
                        u9.showLoading();
                        queryDepartmentContacts().then(function (contacts) {
                            defer.resolve(angular.copy(contacts));
                        }, function () {
                            defer.reject();
                        }).finally(function () {
                            u9.hideLoading();
                        });
                    }

                    return defer.promise;
                };
                o.getFriends = function () {
                    var defer = $q.defer();

                    if (contactsCache.friends) {
                        defer.resolve(angular.copy(contactsCache.friends));
                    } else {
                        u9.showLoading();
                        queryFriends().then(function (contacts) {
                            defer.resolve(angular.copy(contacts));
                        }, function () {
                            defer.reject();
                        }).finally(function () {
                            u9.hideLoading();
                        });
                    }

                    return defer.promise;
                };
                o.managerFriends = function(friendId, isAdd) {
                    var defer = $q.defer();

                    var userId = userInfo.OperaterID;
                    if (userId) {
                        if (isAdd) {
                            checkFriend(friendId.toString()).then(function (isFriends) {
                                if (isFriends) {
                                    defer.reject('该联系人已是您的好友');
                                } else {
                                    OperaterUtil.managerFriends(userId, [friendId], isAdd).then(function (result) {
                                        if (result) {
                                            queryFriends().finally(function () {
                                                defer.resolve(result);
                                            });
                                        } else {
                                            defer.resolve(result);
                                        }
                                    }, function () {
                                        defer.reject();
                                    });
                                }
                            });
                        } else {
                            OperaterUtil.managerFriends(userId, [friendId], isAdd).then(function (result) {
                                if (result) {
                                    queryFriends().finally(function () {
                                        defer.resolve(result);
                                    });
                                } else {
                                    defer.resolve(result);
                                }
                            }, function () {
                                defer.reject();
                            });
                        }
                    } else {
                        defer.reject();
                    }

                    return defer.promise;
                };
                o.checkFriend = function (friendId) {
                    return checkFriend(friendId);
                };
                o.searchOperaters = function (keyword, isQueryFriend) {
                    var defer = $q.defer();

                    var userId = userInfo.OperaterID;
                    if (userId) {
                        OperaterUtil.queryOperaters(keyword, isQueryFriend, userId).then(function (operaters) {
                            var contacts = [];
                            angular.forEach(operaters, function (user) {
                                if (!sealCache.hasOwnProperty(user.OperaterID) && user.Seal) {
                                    sealCache[user.OperaterID] = 'data:image/png;base64,' + user.Seal;
                                }
                                contacts.push({
                                    id: user.OperaterID.toString(),
                                    name: user.OperaterName,
                                    phone: user.Phone || '',
                                    tel: user.Tel || '',
                                    position: user.Postion || '',
                                    email: user.Mail || '',
                                    department: user.Depterment || '',
                                    photo: sealCache[user.OperaterID]
                                });
                            });
                            defer.resolve(contacts);
                        }, function () {
                            defer.reject();
                        });
                    } else {
                        defer.reject([]);
                    }

                    return defer.promise;
                };
                o.getContactDetail = function (id, source) {
                    var contacts = source === 'true' ? contactsCache.departmentContacts : contactsCache.friends,
                        temp, result;
                    if (!contacts) {
                        return {};
                    }
                    for (var i = 0, len = contacts.length; i < len; i++) {
                        temp = contacts[i].items;
                        for (var j = 0, l = temp.length; j < l; j++) {
                            if (temp[j].id === id) {
                                result = angular.copy(temp[j]);
                                break;
                            }
                        }
                        if (result) {
                            break;
                        }
                    }
                    if (result) {
                        return result;
                    } else {
                        return {};
                    }
                };

                return o;

                function queryDepartmentContacts () {
                    var defer = $q.defer();

                    var userCode = u9.getLoginData().UserCode;
                    OperaterUtil.queryDepOperater(userCode).then(function (results) {
                        if (results) {
                            if (results.length > 0 ) {
                                userInfo = results[0];
                            }
                            var formatResults = formatContacts(results);
                            contactsCache.departmentContacts = formatResults;
                            defer.resolve(formatResults);
                        } else {
                            contactsCache.departmentContacts = [];
                            defer.resolve([]);
                        }
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                }
                function queryFriends() {
                    var defer = $q.defer();

                    var userId = userInfo.OperaterID;
                    if (userId) {
                        OperaterUtil.queryOperaterFriends(userId).then(function (results) {
                            var formatResults = formatContacts(results);
                            contactsCache.friends = formatResults;
                            defer.resolve(formatResults);
                        }, function () {
                            defer.reject();
                        });
                    } else {
                        defer.resolve([]);
                    }

                    return defer.promise;
                }
                function checkFriend (friendId) {
                    var defer = $q.defer();

                    o.getFriends().then(function () {
                        var friends = contactsCache.friends,
                            isFriends = false;
                        for (var i = 0, len = friends.length; i < len; i++) {
                            for (var j = 0, t = friends[i].items.length; j < t; j++) {
                                if (friends[i].items[j].id === friendId) {
                                    isFriends = true;
                                    break;
                                }
                            }
                            if (isFriends) {
                                break;
                            }
                        }
                        defer.resolve(isFriends);
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                }
                function formatContacts (users) {
                    var temp = {}, contacts = [], t;
                    angular.forEach(users, function (user) {
                        var camelChars = pinyin.getCamelChars(user.OperaterName);
                        if (camelChars.length > 0) {
                            var camelChar = camelChars[0].toUpperCase();
                            if (!sealCache.hasOwnProperty(user.OperaterID) && user.Seal) {
                                sealCache[user.OperaterID] = 'data:image/png;base64,' + user.Seal;
                            }
                            if (user.Tel && user.Tel[0] === '-') {
                                user.Tel = user.Tel.substr(1);
                            }
                            t = {
                                id: user.OperaterID.toString(),
                                name: user.OperaterName,
                                phone: user.Phone || '',
                                tel: user.Tel,
                                position: user.Postion || '',
                                email: user.Mail || '',
                                department: user.Depterment || '',
                                photo: sealCache[user.OperaterID]
                            };
                            if (temp[camelChar]) {
                                temp[camelChar].push(t);
                            } else {
                                temp[camelChar] = [t];
                            }
                        }
                    });
                    for(var i = 65; i < 91; i++) {
                        var filter = String.fromCharCode(i);
                        if (temp[filter] && temp[filter].length > 0) {
                            contacts.push({
                                group: filter,
                                items: temp[filter]
                            });
                        }
                    }
                    return contacts;
                }
            }
        ])
        .factory('ConnectService', ['$q', 'cordovaCall', 'cordovaSms', 'cordovaEmailComposer',
            function ($q, cordovaCall, cordovaSms, cordovaEmailComposer) {
                var o = {};

                o.call = function (number) {
                    var defer = $q.defer();

                    cordovaCall.call(number).then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                };
                o.sendMsg = function (number) {
                    var defer = $q.defer();

                    cordovaSms.send(number, '', 'INTENT').then(function () {
                        defer.resolve();
                    }, function (err) {
                        defer.reject(err);
                    });

                    return defer.promise;
                };
                o.sendEmail = function (properties) {
                    var defer = $q.defer();

                    cordovaEmailComposer.open(properties).then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                };

                return o;
            }
        ]);
});
